<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="isLook ? '查看' : '编辑'" v-model="visible" align-center width="1300px" :z-index="2000" @close="handleClose">
    <el-form ref="formRef" :model="form" label-width="110px" :disabled="isLook" label-position="top">
      <div class="v-title mb-3 mt-2">基础信息</div>
      <div class="grid grid-cols-4 gap-x-3">
        <el-form-item label="供应商">
          <el-input v-model="form.basic.supplier_name" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item label="供应商类型">
          <VSelect v-model="form.basic.purchase_type" placeholder="请输入" :options="options.purchase_type || []" filterable clearable disabled class="w-full" />
        </el-form-item>
        <el-form-item label="结算方式">
          <el-input v-model="form.basic.period_name" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item label="公司主体">
          <VSelect v-model="form.basic.company_id" placeholder="请输入" :options="options.company_id || []" filterable clearable disabled class="w-full" />
        </el-form-item>
        <el-form-item label="退款类型">
          <VSelect v-model="form.basic.refund_type" placeholder="请输入" :options="options.refund_type || []" filterable clearable disabled
            class="w-full" @change="refundTypeChange" />
        </el-form-item>
        <el-form-item label="来源类型">
          <VSelect v-model="form.basic.source_type" placeholder="请输入" :options="options.source_type || []" filterable clearable class="w-full" disabled />
        </el-form-item>
        <el-form-item label="来源单号">
          <VSelect v-model="form.basic.source_no" placeholder="请输入" disabled :options="options.source_no || []" filterable clearable class="w-full" />
        </el-form-item>
        <el-form-item label="收款账号">
          <el-input v-model="form.basic.refund_account" placeholder="请输入" class="w-full" />
        </el-form-item>
        <div class="grid grid-cols-2 gap-x-3">
          <el-form-item label="退款币种">
            <VSelect v-model="form.basic.refund_currency" placeholder="请输入" :options="options.currency || []" filterable clearable class="w-full" />
          </el-form-item>
          <el-form-item label="退款单号">
            {{ form.basic.refund_no }}
          </el-form-item>
        </div>
        <el-form-item label="1688退款单号">
          <el-link type="primary" @click="open1688(form.basic.platform_refund_no)">{{form.basic.platform_refund_no}}</el-link>
        </el-form-item>
        <el-form-item label="退款交易号">
          <el-input v-model="form.basic.refund_transaction_no" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="收款方式">
          <VSelect v-model="form.basic.refund_method" placeholder="请输入" :options="options.refund_method || []" filterable clearable class="w-full" />
        </el-form-item>
        <el-form-item label="申请退款总金额">
          <el-input-number v-model="apply_refund_total" :controls="false" placeholder="请输入" precision="2" class="w-full"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" class="col-span-full">
          <el-input v-model="form.basic.remark" placeholder="请输入" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" resize="none" />
        </el-form-item>
        <div class="col-span-full">
          <VUpload v-model="form.basic.refund_voucher" title="退款凭证" multiple :types="['jpg', 'jpeg', 'png', 'pdf','xls','xlsx']" class="col-span-full mb-3" />
        </div>
      </div>
      <div class="v-title mb-3 mt-2 flex">
        <div class="flex-1">采购单信息</div>
        <div>
          <VText title="申请退款总金额" :value="apply_refund_total" class="ml-auto" />
        </div>
      </div>
      <vxe-table ref="tableRef" :data="form.purchase" size="small">
        <vxe-column title="采购单号" :min-width="140">
          <template #default="{ row }">
            <el-link type='primary'>{{ row.purchase_no }}</el-link>
          </template>
        </vxe-column>
        <vxe-column title="sku" field="sku" :min-width="100">
          <template #default="{ row }">
            <el-link type='primary'>{{ row.sku }}</el-link>
          </template>
        </vxe-column>
        <vxe-column title="下单金额" field="unit_price" :min-width="100">
          <template #default="{ row }">
            <div><span class='text-gray-500'></span>{{ row.is_drawback === 2 ?
              row.total_purchase_price_tax :
              row.total_purchase_price }}</div>
          </template>
        </vxe-column>
        <vxe-column title="运费" field="tracking_price" :min-width="80" />
        <vxe-column title="优惠" field="discount_price" :min-width="80" />
        <vxe-column title="已退款金额" field="refund_price" :min-width="90" />
        <vxe-column title="可退金额" field="can_refund_price" :min-width="80" />
        <vxe-column title="入库金额" field="inbound_price" :min-width="80" />
        <vxe-column title="已付金额" field="payment_price" :min-width="80" />
        <vxe-column title="未入库金额" field="un_inbound_price" :min-width="90" />
        <vxe-column title="货款退款金额" :min-width="100">
          <template #default="{ row }">
            <el-input-number v-model="row.apply_price" :controls="false" :min="0" :step="0.01" :precision="2" class="w-full" :disabled="form.basic.refund_type === 5" />
          </template>
        </vxe-column>
        <vxe-column title="申请退运费" :min-width="100">
          <template #default="{ row }">
            <el-input-number v-model="row.apply_tracking_refund_price" :controls="false" :min="0" :step="0.01" :precision="2" class="w-full"
              :disabled="form.basic.refund_type !== 5" />
          </template>
        </vxe-column>
        <vxe-column title="操作" width="80">
          <template #default="{rowIndex}">
            <el-button link type="danger" @click="form.purchase.splice(rowIndex, 1)">删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </el-form>
    <template #footer>
      <template v-if="isLook">
        <el-button @click="close">关 闭</el-button>
      </template>
      <template v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loadings[2]" @click="create(2)">确 定</el-button>
        <el-button type="primary" :loading="loadings[1]" @click="create(1)">提 交</el-button>
      </template>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, nextTick, reactive } from 'vue';
import api from '../api'
import { ElMessage } from 'element-plus'
import { resMessage } from '@/utils/res'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
const isLook = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})

// 退款类型变化
const refundTypeChange = type => {
  resetRefund()
}
// 重置金额
const resetRefund = () => {
  form.value.purchase.forEach(d => {
    d.apply_refund_price = d.can_refund_price
    d.apply_tracking_refund_price = form.value.basic.refund_type !== 5 ? 0 : d.tracking_price
    d.apply_refund_price = form.value.basic.refund_type !== 5 ? d.can_refund_price : 0
  })
}

const open1688 = no => {
  window.open(`https://dispute.1688.com/refund/assureRefundDetail.htm?refundId=${no}`, '_blank')
}

// 打开弹窗
const open = async (r_id, option) => {
  isLook.value = !!option?.look
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {
    basic: {},
    purchase: [],
  }
  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()

  if (r_id) {
    const res = await api.detail({ r_id })
    form.value = res.data
  } else {
    form.value.basic.refund_type = 4
    form.value.basic.refund_method = 1
    form.value.basic.refund_voucher = []
    resetRefund()
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

const apply_refund_total = computed(() => {
  const { refund_type } = form.value.basic || {};
  const isRefundType4 = refund_type === 5;
  const total = form.value?.purchase?.reduce((acc, item) => {
    const priceKey = isRefundType4 ?  "apply_tracking_refund_price": "apply_price";
    const price = Number(item?.[priceKey] || 0);
    item.apply_refund_price = item?.apply_price||0;
    item.apply_tracking_price = Number(item?.apply_tracking_refund_price||0)
    return acc + price;
  }, 0);
  // if (form.value.basic) {
  //   form.value.basic.apply_price != isRefundType4 ? total : 0;
  //   form.value.basic.apply_tracking_price = isRefundType4 ? total : 0;
  // }
  return Number((total||0).toFixed(2))
});
watch(apply_refund_total, (newTotal) => {
  if (!form.value.basic) return;
  form.value.basic.apply_price = form.value.basic.refund_type != 5 ? newTotal : 0;
  form.value.basic.apply_tracking_price = form.value.basic.refund_type == 5 ? newTotal : 0;
});
// 提交
const create = async (is_submit) => {
  if (!await formRef?.value.validate()) return
  loadings[is_submit] = true
  form.value.basic.is_submit = is_submit
  // const { purchase, basic } = form.value;
  // let { apply_price_data, apply_tracking_price_data } = purchase?.reduce(
  //   (acc, d) => {
  //     d.apply_refund_price = d.apply_price;
  //     acc.apply_price_data += Number(d.apply_price || 0);
  //     acc.apply_tracking_price_data += Number(d.apply_tracking_price || 0);
  //     return acc;
  //   },
  //   { apply_price_data: 0, apply_tracking_price_data: 0 }
  // );
  // basic.apply_price = apply_price_data;
  // basic.apply_tracking_price = apply_tracking_price_data;
  api.edit(form.value).then(res => {
    resMessage({
      res,
      success: () => {
        ElMessage.success('操作成功')
        emit('success')
        close()
      }
    })
  }).finally(() => {
    loadings[is_submit] = false
  })
}

defineExpose({ open })
</script>